package io.renren.modules.member.controller;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;

public class HttpClientUtils {

    public static void addBinaryBody() throws ClientProtocolException, IOException {
        String textFileName = "f:/下载记录.txt";
        // 创建HttpClient对象
        CloseableHttpClient client = HttpClients.createDefault();

        File file = new File(textFileName);
        HttpPost post = new HttpPost("http://localhost:8080/renren-admin/member/member/upload/idCode");
        String message = "This is a multipart post";
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, textFileName);
        builder.addTextBody("text", message, ContentType.DEFAULT_BINARY);
        //
        HttpEntity entity = builder.build();
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        entity = response.getEntity();
        String result = EntityUtils.toString(entity);
        System.out.println("----------------------" + result);
    }

    public static void main(String[] args) throws Exception {
        HttpClientUtils.addBinaryBody();
    }
}
